package com.pay.ioopos.fragment;

import com.aggregate.pay.sanstar.SanstarApiFactory;
import com.aggregate.pay.sanstar.bean.Result;
import com.aggregate.pay.sanstar.support.Client;
import com.pay.ioopos.ApiFactory;
import com.pay.ioopos.BindState;
import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DataStore;
import com.pay.ioopos.StatusListener;
import com.pay.ioopos.service.PantService;
import com.pay.ioopos.service.ReportService;
import com.pay.ioopos.sqlite.SettingHelper;

import static com.pay.ioopos.fragment.TipFragment.TipType.WAIT;

public class ShopUnbindFragment extends TipVerticalFragment implements BindState {
    private StatusListener listener;

    public ShopUnbindFragment(StatusListener listener) {
        super(WAIT, "正在解绑设备");
        this.listener = listener;
    }

    @Override
    public void execute() throws Exception {

        PantService.online(false);

        Client<Void, Void> client = SanstarApiFactory.terminalUnbind(ApiFactory.initApi());

        Result<Void> apiResult = client.execute(null);

        if (apiResult.getStatus() != Result.Status.OK) {
            onError("[" + apiResult.getCode() + "]" + apiResult.getMessage());
            PantService.online(true);
            return;
        }

        DataStore store = DataFactory.getDataStore();
        store.setMerchNo(null);
        store.setTerminalNo(null);
        store.setTransKey(SettingHelper.INIT_KEY);
        store.setTransPrefix(null);

        ReportService.resetService();

        onSuccess();
    }

    @Override
    public void onError(String msg) {
        speak("设备解绑失败");
        listener.onError(msg);
    }

    private void onSuccess() {
        speak("设备解绑成功");
        listener.onSuccess("设备解绑成功");
    }

    @Override
    public boolean useNetwork() {
        return true;
    }
}
